// 内容脚本
console.log('内容脚本已加载');

// 添加消息监听
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
	if (request.action === "initMarkdownViewer") {
		init();
	}
});

function isMarkdownPage() {
	return window.location.href.includes('.md') ||
		document.querySelector('.markdown-body') !== null ||
		document.querySelector('.file-content') !== null;
}

function createThemeSwitch() {
	if (document.querySelector('.theme-switch-wrapper')) {
		return;
	}

	const switchWrapper = document.createElement('div');
	switchWrapper.className = 'theme-switch-wrapper';

	const label = document.createElement('span');
	label.textContent = '夜间模式';
	label.style.marginRight = '8px';
	label.style.color = '#666';
	switchWrapper.appendChild(label);

	const switchLabel = document.createElement('label');
	switchLabel.className = 'theme-switch';

	const checkbox = document.createElement('input');
	checkbox.type = 'checkbox';

	const slider = document.createElement('span');
	slider.className = 'slider';

	switchLabel.appendChild(checkbox);
	switchLabel.appendChild(slider);
	switchWrapper.appendChild(switchLabel);

	const isDarkMode = localStorage.getItem('darkMode') === 'true';
	checkbox.checked = isDarkMode;
	if (isDarkMode) {
		document.body.classList.add('dark-mode');
	}

	checkbox.addEventListener('change', function() {
		document.body.classList.toggle('dark-mode');
		localStorage.setItem('darkMode', this.checked);
	});

	const container = document.querySelector('.markdown-body') ||
		document.querySelector('.file-content');
	if (container) {
		container.parentElement.style.position = 'relative';
		container.parentElement.appendChild(switchWrapper);
	}
}

// 创建全屏容器
function createFullscreenContainer(markdownContent) {
	// 移除已存在的容器
	const existingContainer = document.querySelector('.markdown-fullscreen-container');
	if (existingContainer) {
		existingContainer.remove();
	}

	const container = document.createElement('div');
	container.className = 'markdown-fullscreen-container';

	// 创建内容包装器
	const contentWrapper = document.createElement('div');
	contentWrapper.className = 'markdown-content-wrapper';
	
	// 克隆原始内容以保留样式和结构
	const clonedContent = markdownContent.cloneNode(true);
	contentWrapper.appendChild(clonedContent);

	// 创建关闭按钮
	const closeButton = document.createElement('button');
	closeButton.className = 'fullscreen-close';
	closeButton.textContent = '返回原页面';
	closeButton.addEventListener('click', () => {
		container.remove();
		document.body.style.overflow = 'auto';
	});

	container.appendChild(closeButton);
	container.appendChild(contentWrapper);
	return container;
}

function createTOC() {
	if (!isMarkdownPage()) return;

	const markdownBody = document.querySelector('.markdown-body') ||
		document.querySelector('.file-content');
	if (!markdownBody) return;

	const headings = markdownBody.querySelectorAll('h1, h2, h3, h4, h5, h6');
	if (headings.length === 0) return;

	// 创建目录容器
	const toc = document.createElement('div');
	toc.className = 'markdown-toc';

	// 创建控制按钮容器
	const tocControls = document.createElement('div');
	tocControls.className = 'toc-controls';

	// 创建主题切换开关
	const switchWrapper = document.createElement('div');
	switchWrapper.className = 'theme-switch-wrapper';
	
	const themeLabel = document.createElement('span');
	themeLabel.textContent = '夜间模式';
	themeLabel.style.color = '#666';
	
	const switchLabel = document.createElement('label');
	switchLabel.className = 'theme-switch';
	
	const checkbox = document.createElement('input');
	checkbox.type = 'checkbox';
	checkbox.checked = localStorage.getItem('darkMode') === 'true';
	
	const slider = document.createElement('span');
	slider.className = 'slider';
	
	switchLabel.appendChild(checkbox);
	switchLabel.appendChild(slider);
	switchWrapper.appendChild(themeLabel);
	switchWrapper.appendChild(switchLabel);

	// 创建收起/展开按钮
	const collapseBtn = document.createElement('button');
	collapseBtn.className = 'toc-collapse-btn';
	collapseBtn.textContent = '收起目录';
	
	// 添加收起/展开功能
	let isCollapsed = false;
	collapseBtn.addEventListener('click', () => {
		isCollapsed = !isCollapsed;
		toc.classList.toggle('collapsed');
		collapseBtn.textContent = isCollapsed ? '展开' : '收起目录';
	});

	// 组装控制按钮区域
	tocControls.appendChild(switchWrapper);
	tocControls.appendChild(collapseBtn);
	toc.appendChild(tocControls);

	// 创建目录列表
	const ul = document.createElement('ul');
	headings.forEach((heading, index) => {
		const level = parseInt(heading.tagName.charAt(1));
		const text = heading.textContent;
		
		const id = `heading-${index}`;
		heading.id = id;
		
		const li = document.createElement('li');
		li.style.marginLeft = `${(level - 1) * 15}px`;
		
		const link = document.createElement('a');
		link.href = `#${id}`;
		link.className = 'toc-link';
		link.textContent = text;
		
		link.addEventListener('click', (e) => {
			e.preventDefault();
			heading.scrollIntoView({ behavior: 'smooth' });
		});
		
		li.appendChild(link);
		ul.appendChild(li);
	});

	toc.appendChild(ul);
	document.body.appendChild(toc);

	// 设置主题切换功能
	checkbox.addEventListener('change', function() {
		document.body.classList.toggle('dark-mode');
		localStorage.setItem('darkMode', this.checked);
	});

	// 如果之前设置了深色模式，应用它
	if (checkbox.checked) {
		document.body.classList.add('dark-mode');
	}
}

function init() {
	console.log('初始化 Markdown 查看器');
	const markdownBody = document.querySelector('.markdown-body') ||
		document.querySelector('.file-content');
	
	if (!markdownBody) {
		console.log('未找到 Markdown 内容');
		return;
	}
	
	createTOC();
}

document.addEventListener('DOMContentLoaded', init);

const observer = new MutationObserver((mutations) => {
	if ((document.querySelector('.markdown-body') ||
			document.querySelector('.file-content')) &&
		!document.querySelector('.markdown-toc')) {
		init();
	}
});

observer.observe(document.body, {
	childList: true,
	subtree: true
});
